package com.zcx.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcx.mapper.RoleMapper;
import com.zcx.mapper.UserMapper;
import com.zcx.mapper.UserRoleMapper;
import com.zcx.pojo.Role;
import com.zcx.pojo.User;
import com.zcx.pojo.UserRole;
import com.zcx.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaochangxin
 * @Title: UserServiceImpl
 * @Package com.zcx.service.impl
 * @Description: UserServiceImpl
 * @date 2022/3/30 17:21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    RoleMapper roleMapper;
    public List<User> queryAllUser(){
        // 首先查询所有用户
        List<User> users = userMapper.selectList(null);
        // 用于存储role_Id的集合
        List<Integer> role_idList = new ArrayList<>();
        for (User user : users) {
            // 循环开始时清空集合
            role_idList.clear();
            // 通过中间表用户user_id和中间表的user_id相等 查询出该用户 有的role_id
            QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",user.getId());
            List<UserRole> userRoles = userRoleMapper.selectList(wrapper);
            // 将查出来的role_id 放入一个List里 好利于BatchIds
            for (UserRole userRole : userRoles) {
                role_idList.add(userRole.getRoleId());
            }
            // 查询该用户所有的Role_Id 有的角色
            if(!userRoles.isEmpty())
            {
                List<Role> roles = roleMapper.selectBatchIds(role_idList);
                user.setRoles(roles);
            }
        }
        return users;
    }
}
